﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Kingdee.BOS.Core.CloudModel;
using Kingdee.BOS.Core.CloudModel.Cloud;
using Newtonsoft.Json;
using Common;

namespace MethodSetBus
{
    public class SAL_SaleOrderBus
    {
        public string Get_SQL_AaleOrder(SaleOrder_OutStock order_OutStock)
        {
			string FDeptNo = "";//部门编码
			string FStaffNo = "";//员工编码

			Root<SAL_SaleOrder> root = new Root<SAL_SaleOrder>();
			root.IsDeleteEntry = "true";
			root.IsVerifyBaseDataField = "false";
			root.IsEntryBatchFill = "true";
			root.ValidateFlag = "true";
			root.NumberSearch = "true";
			root.IsAutoAdjustField = "false";
			root.IsControlPrecision = "false";
			root.ValidateRepeatJson = "false";
			SAL_SaleOrder _SaleOrder = new SAL_SaleOrder();
            try
            {
				string sql = $"exec Get_ObtainDepartmentInfoRmation '{order_OutStock.FSaleSpersonName}'";
				DataTable dt = DBHelper.ExecuteQuery(sql);
                if (dt.Rows.Count > 0)
                {
					FStaffNo = dt.Rows[0]["FStaffNo"].ToString();
					FDeptNo = dt.Rows[0]["FDeptNo"].ToString();
				}
				_SaleOrder.FID = 0;
				_SaleOrder.FBillTypeID = new OrgBase
				{
					FNumber = "XSDD12_SYS"
				};
				_SaleOrder.FDate = order_OutStock.FDate;//DateTime.Now.ToString("yyyy-MM-dd");
				_SaleOrder.FSaleOrgId = new OrgBase
				{
					FNumber = order_OutStock.FOrgNo//"102"
				};
				_SaleOrder.FCustId = new OrgBase
				{
					FNumber = "CUST0301"//order_OutStock.FCustomerNo//"CUST0287"
				};
				_SaleOrder.FReceiveId = new OrgBase
				{
					FNumber = "CUST0301"//order_OutStock.FCustomerNo
				};
				_SaleOrder.FSaleDeptId = new OrgBase//销售部门
				{
					FNumber = FDeptNo
				};
				_SaleOrder.FSalerId = new OrgBase//销售员
				{
					FNumber = FStaffNo
				};
				_SaleOrder.FSettleId = new OrgBase
				{
					FNumber = "CUST0301"//order_OutStock.FCustomerNo
				};
				_SaleOrder.FChargeId = new OrgBase
				{
					FNumber = "CUST0301"//order_OutStock.FCustomerNo
				};
				_SaleOrder.FISINIT = false;
				_SaleOrder.FIsMobile = false;
				_SaleOrder.FIsUseOEMBomPush = false;
				_SaleOrder.FIsUseDrpSalePOPush = false;
				_SaleOrder.FIsCreateStraightOutIN = false;
				//_SaleOrder.FNote = order_OutStock.FNumber;
				_SaleOrder.F_PFKX_LargeText = order_OutStock.FPhoneNumber;
				_SaleOrder.F_PFKX_LargeText1 = order_OutStock.FNumber;
				//地址
				_SaleOrder.FReceiveAddress = order_OutStock.FAddress;
				//联系方式
				_SaleOrder.FLinkPhone = order_OutStock.FPhoneNumber;
				//合同号
				_SaleOrder.F_PFKX_Text = order_OutStock.contract_no;

				_SaleOrder.FSaleOrderEntry = new List<SAL_SaleOrderEntry>();


				decimal StoMoney = 0;
                //明细
                for (int i = 0; i < order_OutStock.Entity.Count; i++)
                {
					string MaterialNo = "";
					string GGXH = "";
					string UnitNo = "";
					decimal TaxRate = 0;

					string SqlEntry = $"exec Get_ObtainMaterialInfoRmation '{order_OutStock.FOrgNo}','{order_OutStock.Entity[i].FMaterialNo}'";
					DataTable dtentry = DBHelper.ExecuteQuery(SqlEntry);
                    if (dtentry.Rows.Count > 0)
                    {
						MaterialNo = dtentry.Rows[0]["FMaterialNo"].ToString();
						GGXH = dtentry.Rows[0]["FSpecification"].ToString();
						UnitNo = dtentry.Rows[0]["FUnitNo"].ToString();
						TaxRate = Convert.ToDecimal(dtentry.Rows[0]["FTAXRATE"].ToString());
					}

					SAL_SaleOrderEntry _SaleOrderEntry = new SAL_SaleOrderEntry();
					_SaleOrderEntry.FRowType = "Standard";
					_SaleOrderEntry.FMaterialId = new OrgBase
					{
						FNumber = order_OutStock.Entity[i].FMaterialNo//"TS01001"
					};
					//_SaleOrderEntry.FMaterialModel = GGXH;
					_SaleOrderEntry.FUnitID = new OrgBase
					{
						FNumber = UnitNo//order_OutStock.Entity[i].FUnitNo//"15"
					};
					_SaleOrderEntry.FQty = Convert.ToDecimal(order_OutStock.Entity[i].FQty);//10;
					_SaleOrderEntry.FPriceUnitId = new OrgBase
					{
						FNumber = UnitNo//order_OutStock.Entity[i].FUnitNo//"15"
					};
					_SaleOrderEntry.FPrice = Convert.ToDecimal(order_OutStock.Entity[i].FPrice);//12;
					_SaleOrderEntry.FTaxPrice = Convert.ToDecimal(order_OutStock.Entity[i].FPrice);
					//税率
					_SaleOrderEntry.FEntryTaxRate = TaxRate;
					//税额
					//_SaleOrderEntry.FEntryTaxAmount = (Convert.ToDecimal(order_OutStock.Entity[i].FQty) * Convert.ToDecimal(order_OutStock.Entity[i].FPrice)*(Convert.ToDecimal(dtentry.Rows[0]["FTAXRATE"].ToString())/100));

					if (order_OutStock.Entity[i].FPrice == 0)
                    {
						_SaleOrderEntry.FIsFree = true;
					}
                    else
                    {
						_SaleOrderEntry.FIsFree = false;
					}
					_SaleOrderEntry.FDeliveryDate = order_OutStock.FDate;
					_SaleOrderEntry.FStockOrgId = new OrgBase
					{
						FNumber = order_OutStock.FOrgNo
					};
					_SaleOrderEntry.FSettleOrgIds = new OrgBase
					{
						FNumber = order_OutStock.FOrgNo
					};
					_SaleOrderEntry.FSupplyOrgId = new OrgBase
					{
						FNumber = order_OutStock.FOrgNo
					};
					_SaleOrderEntry.FOwnerTypeId = "BD_OwnerOrg";
					_SaleOrderEntry.FOwnerId = new OrgBase
					{
						FNumber = order_OutStock.FOrgNo
					};
					_SaleOrderEntry.FReserveType = "1";
					_SaleOrderEntry.FPriceBaseQty = Convert.ToDecimal(order_OutStock.Entity[i].FQty);
					_SaleOrderEntry.FStockUnitID = new OrgBase
					{
						FNumber = UnitNo//order_OutStock.Entity[i].FUnitNo//"15"
					};
					_SaleOrderEntry.FStockQty = Convert.ToDecimal(order_OutStock.Entity[i].FQty);
					_SaleOrderEntry.FStockBaseQty = Convert.ToDecimal(order_OutStock.Entity[i].FQty);
					_SaleOrderEntry.FOUTLMTUNIT = "SAL";
					_SaleOrderEntry.FOutLmtUnitID = new OrgBase
					{
						FNumber = UnitNo//order_OutStock.Entity[i].FUnitNo
					};
					_SaleOrderEntry.FISMRP = false;
					_SaleOrderEntry.FAllAmount = order_OutStock.Entity[i].FSubtotal;//(Convert.ToDecimal(order_OutStock.Entity[i].FQty) * Convert.ToDecimal(order_OutStock.Entity[i].FPrice));
					_SaleOrderEntry.FAllAmountExceptDisCount = order_OutStock.Entity[i].FSubtotal;//(Convert.ToDecimal(order_OutStock.Entity[i].FQty) * Convert.ToDecimal(order_OutStock.Entity[i].FPrice));
					_SaleOrderEntry.FOrderEntryPlan = new List<SAL_SaleOrderEntryPlan>();
					SAL_SaleOrderEntryPlan _SaleOrderEntryPlan = new SAL_SaleOrderEntryPlan();
					_SaleOrderEntryPlan.FDetailLocAddress = order_OutStock.FAddress ;
					_SaleOrderEntryPlan.FPlanDate = order_OutStock.FDate; //DateTime.Now.ToString("yyyy-MM-dd");
					_SaleOrderEntryPlan.FPlanQty = Convert.ToDecimal(order_OutStock.Entity[i].FQty);
					_SaleOrderEntry.FOrderEntryPlan.Add(_SaleOrderEntryPlan);
					_SaleOrder.FSaleOrderEntry.Add(_SaleOrderEntry);

					StoMoney = StoMoney + Convert.ToDecimal(order_OutStock.Entity[i].FSubtotal);

				}
				//运费
                if (Convert.ToDecimal(order_OutStock.ship_price) !=0)
                {
					string SqlEntry = $"exec Get_ObtainMaterialInfoRmation '{order_OutStock.FOrgNo}','10.9999.001'";
					DataTable dtentryYF = DBHelper.ExecuteQuery(SqlEntry);
					SAL_SaleOrderEntry _SaleOrderEntry = new SAL_SaleOrderEntry();
					_SaleOrderEntry.FRowType = "Standard";
					_SaleOrderEntry.FMaterialId = new OrgBase
					{
						FNumber = "10.9999.001"
					};
					_SaleOrderEntry.FUnitID = new OrgBase
					{
						FNumber = "Pcs"
					};
					_SaleOrderEntry.FQty = 1;//10;
					_SaleOrderEntry.FPriceUnitId = new OrgBase
					{
						FNumber = "Pcs"
					};
					_SaleOrderEntry.FPrice = Convert.ToDecimal(order_OutStock.ship_price);//12;
					_SaleOrderEntry.FTaxPrice = Convert.ToDecimal(order_OutStock.ship_price);
					_SaleOrderEntry.FEntryTaxRate = Convert.ToDecimal(dtentryYF.Rows[0]["FTAXRATE"].ToString()); ;
					_SaleOrderEntry.FIsFree = false;
					_SaleOrderEntry.FDeliveryDate = order_OutStock.FDate;
					_SaleOrderEntry.FStockOrgId = new OrgBase
					{
						FNumber = order_OutStock.FOrgNo
					};
					_SaleOrderEntry.FSettleOrgIds = new OrgBase
					{
						FNumber = order_OutStock.FOrgNo
					};
					_SaleOrderEntry.FSupplyOrgId = new OrgBase
					{
						FNumber = order_OutStock.FOrgNo
					};
					_SaleOrderEntry.FOwnerTypeId = "BD_OwnerOrg";
					_SaleOrderEntry.FOwnerId = new OrgBase
					{
						FNumber = order_OutStock.FOrgNo
					};
					_SaleOrderEntry.FReserveType = "1";
					_SaleOrderEntry.FPriceBaseQty = 1;
					_SaleOrderEntry.FStockUnitID = new OrgBase
					{
						FNumber = "Pcs"
					};
					_SaleOrderEntry.FStockQty = 1;
					_SaleOrderEntry.FStockBaseQty = 1;
					_SaleOrderEntry.FOUTLMTUNIT = "SAL";
					_SaleOrderEntry.FOutLmtUnitID = new OrgBase
					{
						FNumber = "Pcs"
					};
					_SaleOrderEntry.FISMRP = false;
					_SaleOrderEntry.FAllAmount = order_OutStock.ship_price;
					_SaleOrderEntry.FAllAmountExceptDisCount = order_OutStock.ship_price;
					_SaleOrderEntry.FOrderEntryPlan = new List<SAL_SaleOrderEntryPlan>();
					SAL_SaleOrderEntryPlan _SaleOrderEntryPlan = new SAL_SaleOrderEntryPlan();
					_SaleOrderEntryPlan.FDetailLocAddress = order_OutStock.FAddress;
					_SaleOrderEntryPlan.FPlanDate = order_OutStock.FDate; //DateTime.Now.ToString("yyyy-MM-dd");
					_SaleOrderEntryPlan.FPlanQty = 1;
					_SaleOrderEntry.FOrderEntryPlan.Add(_SaleOrderEntryPlan);
					_SaleOrder.FSaleOrderEntry.Add(_SaleOrderEntry);
				}
				//财务信息
				SAL_SaleOrderFinance _SaleOrderFinance = new SAL_SaleOrderFinance();
				_SaleOrderFinance.FSettleCurrId = new OrgBase
				{
					FNumber = "PRE001"
				};
				_SaleOrderFinance.FIsPriceExcludeTax = true;
				_SaleOrderFinance.FIsIncludedTax = true;
				_SaleOrderFinance.FExchangeTypeId = new OrgBase
				{
					FNumber = "HLTX01_SYS"
				};
				_SaleOrderFinance.FOverOrgTransDirect = false;

				//价税合计
				_SaleOrderFinance.FBillAllAmount = Convert.ToDecimal(order_OutStock.deal_price);
				//价税合计
				_SaleOrderFinance.FBillAllAmount_LC = Convert.ToDecimal(order_OutStock.deal_price);

				_SaleOrderFinance.FAllDisCount = (StoMoney + Convert.ToDecimal(order_OutStock.ship_price) - Convert.ToDecimal(order_OutStock.deal_price));//整单折扣额

				_SaleOrder.FSaleOrderFinance = new SAL_SaleOrderFinance();
				_SaleOrder.FSaleOrderFinance = _SaleOrderFinance;

				//收款计划
				_SaleOrder.FSaleOrderPlan = new List<SAL_SaleOrderPlan>();
				SAL_SaleOrderPlan _SaleOrderPlan = new SAL_SaleOrderPlan();
				_SaleOrderPlan.FNeedRecAdvance = false;
				_SaleOrderPlan.FRecAdvanceRate = 100;
				_SaleOrderPlan.FRecAdvanceAmount = order_OutStock.deal_price;
				_SaleOrderPlan.FIsOutStockByRecamount = false;
				_SaleOrder.FSaleOrderPlan.Add(_SaleOrderPlan);



				root.Model = _SaleOrder;

				return JsonConvert.SerializeObject(root);
            }
            catch (Exception e)
            {
				return JsonConvert.SerializeObject(root);
			}
        }

		/// <summary>
		/// 非空校验
		/// </summary>
		/// <param name="TypeData"></param>
		/// <returns></returns>
		public IsSuccessResult IsNullClounm(DataType<SaleOrder_OutStock> TypeData)
        {
			IsSuccessResult isSuccess = new IsSuccessResult();
			/*if (string.IsNullOrEmpty(TypeData.Type))
			{
				isSuccess.Code = 100;
				isSuccess.Result = null;
				isSuccess.Message = "请输入有效类型！(Type)";
				return isSuccess;
			}*/
			if (string.IsNullOrEmpty(TypeData.Data.FNumber))
			{
				isSuccess.Code = 100;
				isSuccess.Result = null;
				isSuccess.Message = "单据编码不可为空！";
				return isSuccess;
			}
			if (string.IsNullOrEmpty(TypeData.Data.FDate))
			{
				isSuccess.Code = 100;
				isSuccess.Result = null;
				isSuccess.Message = "下单日期不可为空！";
				return isSuccess;
			}
			if (string.IsNullOrEmpty(TypeData.Data.FOrgNo))
			{
				isSuccess.Code = 100;
				isSuccess.Result = null;
				isSuccess.Message = "组织编码不可为空！";
				return isSuccess;
			}
            else if(TypeData.Data.FOrgNo!="100" && TypeData.Data.FOrgNo!="101")
            {
				isSuccess.Code = 100;
				isSuccess.Result = null;
				isSuccess.Message = "组织编码无法识别！";
				return isSuccess;
			}
			if (string.IsNullOrEmpty(TypeData.Data.FPhoneNumber))
			{
				isSuccess.Code = 100;
				isSuccess.Result = null;
				isSuccess.Message = "收货人手机号不可为空！";
				return isSuccess;
			}
			if (string.IsNullOrEmpty(TypeData.Data.FAddress))
			{
				isSuccess.Code = 100;
				isSuccess.Result = null;
				isSuccess.Message = "收货地址不可为空！";
				return isSuccess;
			}
			if (string.IsNullOrEmpty(TypeData.Data.ship_price.ToString()))
			{
				isSuccess.Code = 100;
				isSuccess.Result = null;
				isSuccess.Message = "运费不可为空！";
				return isSuccess;
			}
			if (string.IsNullOrEmpty(TypeData.Data.deal_price.ToString()))
			{
				isSuccess.Code = 100;
				isSuccess.Result = null;
				isSuccess.Message = "订单价格不可为空！";
				return isSuccess;
			}
			for (int i = 0; i < TypeData.Data.Entity.Count; i++)
            {
				if (string.IsNullOrEmpty(TypeData.Data.Entity[i].FMaterialNo))
				{
					isSuccess.Code = 100;
					isSuccess.Result = null;
					isSuccess.Message = "商品编码不可为空！";
					return isSuccess;
				}
				if (string.IsNullOrEmpty(TypeData.Data.Entity[i].FPrice.ToString()))
				{
					isSuccess.Code = 100;
					isSuccess.Result = null;
					isSuccess.Message = "单价不可为空！";
					return isSuccess;
				}
				if (TypeData.Data.Entity[i].FQty == null || TypeData.Data.Entity[i].FQty == 0)
				{
					isSuccess.Code = 100;
					isSuccess.Result = null;
					isSuccess.Message = "数量不可为空！";
					return isSuccess;
				}
				if ( string.IsNullOrEmpty(TypeData.Data.Entity[i].FSubtotal.ToString()))
				{
					isSuccess.Code = 100;
					isSuccess.Result = null;
					isSuccess.Message = "小计不可为空！";
					return isSuccess;
				}
			}

			isSuccess.Code = 0;
			isSuccess.Result = null;
			isSuccess.Message = null;
			return isSuccess;
		}
    }
}
